package com.boot.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.boot.constant.InterceptorConstants;
import com.boot.resp.Response;
import com.boot.util.BeanJsonUtil;
import com.boot.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.Map;

/**

 */
public class AuthTokenInterceptor {//extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(AuthTokenInterceptor.class);

    private static final String HEADER = "header";

    private static final String CHANNEL = "channel";

    private static final String TOKEN = "token";

    private static final String LANGUAGE = "language";

    private static final String CURRENTID = "currentId";

    private static final String ROLE_KEY = "user_role_%d";


   // @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, MalformedURLException {

        // 获取否methodHandler
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 打印出所有传入参数
        if (log.isDebugEnabled()) {
            Enumeration<String> pnames = request.getParameterNames();
            StringBuffer pnsb = new StringBuffer();
            while (pnames.hasMoreElements()) {
                String name = (String) pnames.nextElement();
                String value = request.getParameter(name);
                pnsb.append(name + ":" + value + ";");
            }
            log.debug("请求{}传入参数为{}", request.getRequestURI(), pnsb.toString());
        }
        // 跳过非API接口
        String uri = request.getRequestURI();
        // 获取请求参数
        String data = CommonUtils.getRequestData(request);
        // 拦截业务操作需要登录
        if (uri.startsWith(InterceptorConstants.OWNER)) {
            if (!StringUtils.hasText(data)) {
                responseJson(response, new Response(InterceptorConstants.NO_AUTHORITY, InterceptorConstants.NO_LOGIN_MESSAGE_EN));
                return false;
            }
            Map map = BeanJsonUtil.json2Object(data, Map.class);
            if (map == null) {
                responseJson(response, new Response(InterceptorConstants.NO_AUTHORITY, InterceptorConstants.NO_LOGIN_MESSAGE_EN));
                return false;
            }
            JSONObject json = (JSONObject) map.get(HEADER);
            String enToken = json.getString(TOKEN);
            String languages = json.getString(LANGUAGE);
            String currentIds = json.getString(CURRENTID);
            String channels = json.getString(CHANNEL);
            if (!StringUtils.hasText(enToken) || !StringUtils.hasText(languages) || !StringUtils.hasText(currentIds) || !StringUtils.hasText(channels)) {
                responseJson(response, new Response(InterceptorConstants.NO_AUTHORITY, InterceptorConstants.NO_LOGIN_PAM_MESSAGE));
                return false;
            }

        }
        request.setAttribute(InterceptorConstants.JSON, data);
        return true;
    }

   // @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }


    private void responseJson(HttpServletResponse response, Response back) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            String json = BeanJsonUtil.bean2Json(back);
            log.info("拦截器返回：-------" + json);
            writer.print(json);
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
